package org.jackysoft.security.config;

import java.io.IOException;
import java.util.Collection;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.jackysoft.entity.AcegiRole;
import org.jackysoft.entity.LoginPage;
import org.jackysoft.entity.User;
import org.jackysoft.util.SpringSecurityUtils;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;

public class MultiUrlAuthenticationSuccessHandler extends
SavedRequestAwareAuthenticationSuccessHandler {
	static final String DEFAULT_LOGIN="/login";
	public MultiUrlAuthenticationSuccessHandler() {
		setDefaultTargetUrl("/index.jsp");
	}

	public MultiUrlAuthenticationSuccessHandler(String defaultTargetUrl) {
		setDefaultTargetUrl(defaultTargetUrl);
	}

	private String fetchTargetUrl(HttpServletRequest request,
			HttpServletResponse response, Authentication authentication) {
		
		Collection<? extends GrantedAuthority> auths = authentication.getAuthorities();
		if (auths == null || auths.size() == 0)
			return this.determineTargetUrl(request, response);
		User user = (User) authentication.getPrincipal();
		AcegiRole secu = user.getPrimarySecurityRole();
		if (secu == null) return 	DEFAULT_LOGIN;
		LoginPage lpage = secu.getLoginIndex();
		if (lpage == null) return 	DEFAULT_LOGIN;		
		return lpage.getUri();

	}

	@Override
	protected void handle(HttpServletRequest request,
			HttpServletResponse response, Authentication authentication)
			throws IOException, ServletException {
		String targetUrl = fetchTargetUrl(request, response, authentication);
		if (response.isCommitted()) {
			logger.debug("响应已经提交. 不能重定向到URL地址 : " + targetUrl);
			return;
		}
		String preUrl = (String) request.getSession().getAttribute(SpringSecurityUtils.VISITED_URL);
		request.getSession().removeAttribute(SpringSecurityUtils.VISITED_URL); 
		targetUrl=preUrl==null?targetUrl:preUrl;
		getRedirectStrategy().sendRedirect(request, response, targetUrl);
	}

}